<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>渔菜学苑 AI助手</title>
    <script src="https://lf-cdn.coze.cn/obj/unpkg/flow-platform/chat-app-sdk/1.2.0-beta.10/libs/cn/index.js"></script>
    <style>
        /* 设备选择弹窗样式 */
        .device-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 10000;
            justify-content: center;
            align-items: center;
        }
        
        .device-modal-content {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            width: 90%;
            max-width: 500px;
            max-height: 70vh;
            overflow-y: auto;
        }
        
        .device-modal-content h3 {
            margin-top: 0;
            text-align: center;
        }
        
        .device-list {
            list-style: none;
            padding: 0;
        }
        
        .device-item {
            padding: 12px;
            margin-bottom: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        
        .device-item:hover {
            background-color: #f0f0f0;
        }
        
        .device-item.selected {
            background-color: #e3f2fd;
            border-color: #2196f3;
        }
        
        .device-sensors {
            margin-top: 8px;
            padding-left: 20px;
            font-size: 0.9em;
            color: #666;
        }
        
        .modal-buttons {
            margin-top: 20px;
            text-align: right;
        }
        
        .modal-btn {
            padding: 8px 16px;
            margin-left: 8px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        
        .confirm-btn {
            background-color: #2196f3;
            color: white;
        }
        
        .cancel-btn {
            background-color: #f5f5f5;
            color: #333;
        }
        
        /* 悬浮切换图标样式 */
        .device-switcher {
            position: fixed;
            bottom: 20px;
            right: 20px;
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background-color: #2196f3;
            color: white;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
            z-index: 9999;
            transition: background-color 0.2s;
        }
        
        .device-switcher:hover {
            background-color: #1976d2;
        }
        
        .device-switcher-icon {
            font-size: 24px;
        }
    </style>
</head>
<body>
    <!-- 设备选择弹窗 -->
    <div id="deviceModal" class="device-modal">
        <div class="device-modal-content">
            <h3>选择设备</h3>
            <ul id="deviceList" class="device-list"></ul>
            <div class="modal-buttons">
                <button class="modal-btn cancel-btn" onclick="closeDeviceModal()">取消</button>
                <button class="modal-btn confirm-btn" onclick="confirmDeviceSelection()">确定</button>
            </div>
        </div>
    </div>
    
    <!-- 悬浮切换图标 -->
    <div id="deviceSwitcher" class="device-switcher" title="切换设备">
        <span class="device-switcher-icon">📱</span>
    </div>
    
    <script>
        // 存储当前选中的设备数据
        let selectedDevice = null;
        let allDevices = [];
        
        // 获取URL参数
        const urlParams = new URLSearchParams(window.location.search);
        const userId = urlParams.get('userId');
        const token = "testtoken";
        
        // Bot ID配置
        const botIdType = "{{botId}}";
        let botId = "7547979490996797455";
        if(botIdType == "yczw"){
            botId = "7546392393412034612";
        }else if(botIdType == "ycxy"){
            botId = "7547979490996797455";
        }
        
        // 获取设备列表
        function fetchDeviceList() {
            return new Promise((resolve, reject) => {
                // 检查userId和token是否存在
                if (!userId || !token) {
                    console.error('缺少userId或token参数');
                    reject(new Error('缺少userId或token参数'));
                    return;
                }
                
                // 使用fetch API发送请求
                fetch(`https://iot.nongzhengqimin.com/ycxy-api/weixin/api/device/simplist?userId=${encodeURIComponent(userId)}&token=${encodeURIComponent(token)}`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应错误');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.code === '200') {
                        allDevices = data.data || [];
                        handleDeviceList(allDevices);
                        resolve(allDevices);
                    } else if (data.code === '401') {
                        console.error('未授权访问');
                        reject(new Error('未授权访问'));
                        // 可以考虑跳转到登录页
                    } else {
                        console.error('获取设备列表失败:', data.msg);
                        reject(new Error('获取设备列表失败: ' + data.msg));
                    }
                })
                .catch(error => {
                    console.error('请求设备列表时发生错误:', error);
                    reject(error);
                });
            });
        }
        
        // 处理设备列表
        function handleDeviceList(devices) {
            if (!devices || devices.length === 0) {
                console.log('没有找到设备');
                return;
            }
            
            if (devices.length === 1) {
                // 只有一个设备，直接存储
                selectedDevice = devices[0];
                console.log('自动选择了唯一设备:', selectedDevice.name);
            } else {
                // 多个设备，显示选择弹窗
                showDeviceModal(devices);
            }
        }
        
        // 显示设备选择弹窗
        function showDeviceModal(devices) {
            const deviceList = document.getElementById('deviceList');
            deviceList.innerHTML = '';
            
            devices.forEach(device => {
                const li = document.createElement('li');
                li.className = 'device-item';
                li.dataset.deviceId = device.id;
                
                // 设备名称
                const deviceName = document.createElement('div');
                deviceName.textContent = device.name;
                li.appendChild(deviceName);
                
                // 传感器列表
                if (device.sensors && device.sensors.length > 0) {
                    const sensorsDiv = document.createElement('div');
                    sensorsDiv.className = 'device-sensors';
                    sensorsDiv.textContent = '传感器: ' + device.sensors.map(s => s.name).join(', ');
                    li.appendChild(sensorsDiv);
                }
                
                // 点击选择设备
                li.addEventListener('click', function() {
                    // 移除其他设备的选中状态
                    document.querySelectorAll('.device-item').forEach(item => {
                        item.classList.remove('selected');
                    });
                    // 添加当前设备的选中状态
                    this.classList.add('selected');
                });
                
                deviceList.appendChild(li);
            });
            
            // 显示弹窗
            document.getElementById('deviceModal').style.display = 'flex';
            
            // 默认选中第一个设备
            if (deviceList.firstChild) {
                deviceList.firstChild.classList.add('selected');
            }
        }
        
        // 关闭设备选择弹窗
        function closeDeviceModal() {
            document.getElementById('deviceModal').style.display = 'none';
        }
        
        // 确认设备选择
        function confirmDeviceSelection() {
            const selectedItem = document.querySelector('.device-item.selected');
            if (selectedItem) {
                const deviceId = selectedItem.dataset.deviceId;
                selectedDevice = allDevices.find(device => device.id === deviceId);
                console.log('已选择设备:', selectedDevice.name);
            }
            closeDeviceModal();
        }
        
        // 切换设备
        function toggleDeviceSelection() {
            if (allDevices.length > 1) {
                showDeviceModal(allDevices);
            } else if (allDevices.length === 1) {
                alert('当前只有一个设备: ' + allDevices[0].name);
            } else {
                alert('没有找到设备');
            }
        }
        
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化聊天SDK
            let chatSdk = new CozeWebSDK.WebChatClient({
                config: {
                    bot_id: botId,
                    appInfo: {
                        parameters: {
                            user_id: "{{userId}}",
                            user_name: "测试用户名"
                        }
                    },
                    botInfo: {
                        parameters: {
                            client_id: '111',
                            client_list: {
                                "灯光:":"kdjfsjdlfkdsfsdf",
                                "水循环":"998990000"
                            },
                            user_id: "{{userId}}",
                        }
                    },
                },
                componentProps: {
                    title: '渔菜学苑',
                },
                "auth": {
                    "type": "token",
                    "token": "{{access_token}}",
                    onRefreshToken: async () => {
                        console.log("token已经过期，需要调用refresh token 刷新token");
                        window.location.href = "/kz/login?userId={{userId}}";
                    }
                },
                userInfo: {
                    id: userId,
                    url: 'https://p3-flow-imagex-sign.byteimg.com/ocean-cloud-tos/FileBizType.BIZ_BOT_ICON/4417200264054228_1757401026665903956_HDisTQu7bE.jpg~tplv-a9rns2rl98-image-qvalue.jpeg?rk3s=bbd3e7ed&x-expires=1761096179&x-signature=ORk1db5SfY9ibf8ezzyc9YFarIg%3D',
                    nickname: '您', 
                },
                ui: {
                    base: {
                        icon: 'https://p3-flow-imagex-sign.byteimg.com/ocean-cloud-tos/FileBizType.BIZ_BOT_ICON/4417200264054228_1757401026665903956_HDisTQu7bE.jpg~tplv-a9rns2rl98-image-qvalue.jpeg?rk3s=bbd3e7ed&x-expires=1761096179&x-signature=ORk1db5SfY9ibf8ezzyc9YFarIg%3D',
                        layout: 'mobile',
                        zIndex: 1000,
                    },
                    asstBtn: {
                        isNeed: false,
                    }, 
                    header: {
                        isShow: false,
                        isNeedClose: false,
                    },
                    footer: {
                        isShow: false,
                        expressionText: '测试文字',
                    },
                    chatBot: {
                        title: "渔菜学苑",
                        onHide: () => {
                            console.log("聊天框隐藏");
                        },
                        onShow: () => {
                            console.log("显示聊天框");
                        }
                    }
                }
            });
            
            // 显示聊天机器人
            chatSdk.showChatBot();
            
            // 绑定悬浮切换图标的点击事件
            document.getElementById('deviceSwitcher').addEventListener('click', toggleDeviceSelection);
            
            // 获取设备列表
            fetchDeviceList();
        });
    </script>
</body>
</html>